package kernal;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class WorkRunnable implements Runnable {
	private final String srcfile;
	private final String dstfile;
	private final int IMG_HEIGHT = 1200;
	private final int IMG_WIDTH = 1600;

	/**
	 * @param src
	 * @param dst
	 */
	public WorkRunnable(String src, String dst) {
		this.srcfile = src;
		this.dstfile = dst;

	}

	public void run() {
		try {
			onResizeImage(this.srcfile, this.dstfile);
		} catch (IOException e) {
			System.out.println("IOException:" + e.getMessage());
		}
	}

	protected void finalize() throws Throwable {
		try {
			System.out.println("[WorkRunnable][finalize] dst:" + dstfile);
		} finally {
			super.finalize();
		}
	}

	/**
	 * @param src
	 * @param dst
	 * @throws IOException
	 */
	public void onResizeImage(String src, String dst) throws IOException {
		File imgFile = new File(src);
		BufferedImage bufImg = ImageIO.read(imgFile);

		int type = bufImg.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : bufImg.getType();

		BufferedImage bufImgResize = resizeImage(bufImg, type);
		File imgResize = new File(dst);
		ImageIO.write(bufImgResize, "jpg", imgResize);

		bufImg.flush();
		bufImgResize.flush();
		imgResize = null;
		imgFile = null;
		bufImgResize = null;
		bufImg = null;
	}

	/**
	 * @param originalImage
	 * @param type
	 * @return
	 */
	private BufferedImage resizeImage(BufferedImage originalImage, int type) {
		BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
		Graphics2D g = resizedImage.createGraphics();
		g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
		g.dispose();
		return resizedImage;
	}

}